package com.yami.shop.user.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ResponseEnum;
import com.yami.shop.user.common.dao.UserGasInfoMapper;
import com.yami.shop.user.common.model.UserGasInfo;
import com.yami.shop.user.common.service.UserGasInfoService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;



@Service
public class UserGasInfoServiceImpl extends ServiceImpl<UserGasInfoMapper, UserGasInfo> implements UserGasInfoService {

    /**
     * 加gas值
     * @param userId
     * @param gasNumber
     * @param
     */
    @Override
    public void saveGasNumberByUserId(String userId, int gasNumber) {
        LambdaQueryWrapper<UserGasInfo> eq = new LambdaQueryWrapper<UserGasInfo>().eq(UserGasInfo::getUserId, userId);
        UserGasInfo userGasInfo = this.getOne(eq);
        if(ObjectUtils.isNotEmpty(userGasInfo)){
            userGasInfo.setGasNumber(userGasInfo.getGasNumber()+gasNumber);
            this.updateById(userGasInfo);
        }else{
            userGasInfo = new UserGasInfo();
            userGasInfo.setGasNumber(gasNumber);
            userGasInfo.setUserId(userId);
            this.save(userGasInfo);
        }
    }

    /**
     * 扣减gas值
     * @param userId
     * @param gasNumber
     * @param
     */
    @Override
    public void reduceGasNumberByUserId(String userId, int gasNumber) {
        LambdaQueryWrapper<UserGasInfo> eq = new LambdaQueryWrapper<UserGasInfo>().eq(UserGasInfo::getUserId, userId);
        UserGasInfo userGasInfo = this.getOne(eq);
        if(ObjectUtils.isEmpty(userGasInfo) || ObjectUtils.isEmpty(userGasInfo.getGasNumber())){
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "用户能量不足");
        }
        if(userGasInfo.getGasNumber() == 0){
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "用户能量不足");
        }
        if(userGasInfo.getGasNumber()-gasNumber < 0){
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "用户能量不足");
        }
        userGasInfo.setGasNumber(userGasInfo.getGasNumber()-gasNumber);
        this.updateById(userGasInfo);
    }

    @Override
    public Boolean checkHaveGasNumberByUserId(String userId, int gasNumber) {
        LambdaQueryWrapper<UserGasInfo> eq = new LambdaQueryWrapper<UserGasInfo>().eq(UserGasInfo::getUserId, userId);
        UserGasInfo userGasInfo = this.getOne(eq);
        if(ObjectUtils.isEmpty(userGasInfo) || ObjectUtils.isEmpty(userGasInfo.getGasNumber()) || userGasInfo.getGasNumber() == 0 || userGasInfo.getGasNumber()-gasNumber < 0){
            return false;
        }else{
            return true;
        }
    }

}
